package org.dragonfire.config;

import java.util.Enumeration;
import java.util.HashSet;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Set;

/**
 * @author Darth Android
 * @date Mar 4, 2007
 */
public class ResourceConfig {

	private Set<String> keySet;
	private ResourceBundle resource;

	public ResourceConfig(String name) {
		resource = ResourceBundle.getBundle(name);
	}

	public String getString(String key) {
		try {
			return resource.getString(key);
		} catch (MissingResourceException e) {
			// throw new RuntimeException("Key '"+key+"' not found in
			// configuration file.");
			return "{" + key.toUpperCase() + "}";
		}
	}

	public String getString(String key, Object... params) {
		return String.format(getString(key), params);
	}

	public int getInt(String key) {
		try {
			return Integer.parseInt(getString(key));
		} catch (NumberFormatException e) {
			throw new RuntimeException("Key '" + key + "' does not contain a valid integer.");
		}
	}

	public String[] getKeys() {
		return getKeySet().toArray(new String[0]);
	}

	/**
	 * Returns a <code>Set</code> of the keys contained <em>only</em> in
	 * this <code>ResourceBundle</code>.
	 * <p>
	 * The default implementation returns a <code>Set</code> of the keys
	 * returned by the {@link #getKeys() getKeys} method except for the ones for
	 * which the {@link #handleGetObject(String) handleGetObject} method returns
	 * <code>null</code>. Once the <code>Set</code> has been created, the
	 * value is kept in this <code>ResourceBundle</code> in order to avoid
	 * producing the same <code>Set</code> in the next calls. Override this
	 * method in subclass implementations for faster handling.
	 * 
	 * @return a <code>Set</code> of the keys contained only in this
	 *         <code>ResourceBundle</code>
	 * @since 1.6
	 */
	private Set<String> getKeySet() {
		if (keySet == null) {
			synchronized (resource) {
				if (keySet == null) {
					Set<String> keys = new HashSet<String>();
					Enumeration<String> enumKeys = resource.getKeys();
					while (enumKeys.hasMoreElements()) {
						String key = enumKeys.nextElement();
						keys.add(key);
					}
					keySet = keys;
				}
			}
		}
		return keySet;
	}
}
